package cn.edu.bupt.freewings.forum.server.rest.providers;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.MessageBodyWriter;
import com.google.protobuf.Message;

@Produces("application/proto")
@Provider
public class ProtoBufferWriter implements MessageBodyWriter<Message>{

	static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ProtoBufferWriter.class); 
	
	static MediaType protoMediaType = MediaType.valueOf("application/proto");
	
	public long getSize(Message message, Class<?> clasz, Type type,
			Annotation[] annotations, MediaType mediaType) {
		logger.info("set size to" + message.getSerializedSize());
		return mediaType.isCompatible(protoMediaType) ? message.getSerializedSize() : -1;
	}

	public boolean isWriteable(Class<?> clasz, Type type, Annotation[] annotations,
			MediaType mediaType) {
		return Message.class.isAssignableFrom(clasz) && mediaType.isCompatible(protoMediaType);
	}

	public void writeTo(Message message, Class<?> clasz, Type type,
			Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
			OutputStream outputStream) throws IOException, WebApplicationException {
		logger.info(message.getAllFields().keySet().toString());
		message.writeTo(outputStream);
	}

}
